﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace Husb.Web.Ioc
{
    public class UnityDependencyResolver : IDependencyResolver
    {
        IUnityContainer container;
        public UnityDependencyResolver(IUnityContainer container)
        {
            this.container = container;
        }

        public object GetService(Type serviceType)
        {
            if (!container.IsRegistered(serviceType))
            {
                if (serviceType.IsAbstract || serviceType.IsInterface)
                {
                    return null;
                }
            }

            try
            {
                if (typeof(IController).IsAssignableFrom(serviceType))
                    return container.Resolve(serviceType);
                else
                    return container.IsRegistered(serviceType) ? container.Resolve(serviceType) : null;
                //return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException rfe)
            {
                WriteLog("================" + DateTime.Now + "===============" + System.Environment.NewLine + rfe.Message + System.Environment.NewLine + rfe.StackTrace + System.Environment.NewLine);
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch
            {
                return new List<object>();
            }
        }


        private static void WriteLog(string message)
        {

            #region Log
            string path = "";
            if (System.Environment.CurrentDirectory == AppDomain.CurrentDomain.BaseDirectory)
            {
                path = AppDomain.CurrentDomain.BaseDirectory;
            }
            else
            {
                path = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\";
            }

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            string logFile = path + DateTime.Now.ToString("yyyyMMdd") + ".log";
            if (!System.IO.File.Exists(logFile))
            {
                System.IO.FileStream log = System.IO.File.Create(logFile);
                log.Close();
            }
            #endregion

            using (System.IO.StreamWriter w = System.IO.File.AppendText(logFile))
            {
                w.WriteLine(message);
            }
        }
    }
}
